package com.woniu.woniu_bx.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.woniu.woniu_bx.pojo.Moment;
import com.woniu.woniu_bx.pojo.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface MomentMapper extends BaseMapper<Moment> {


    //根据用户id查询动态
    @Select("select * from bx_moment where user_id = #{id} order by time")
    List<Moment> findByUserId(int id);

    //查询我关注的人的头像、id、昵称、动态及其评论和子评论
    @Select("select bu2.id,bu2.nick,bu2.avr from bx_user bu,bx_user bu2 ,bx_like bl where bu.id=bl.user_id and bu2.id=bl.belike_id and bu.id=#{id}")
    @Results({
            @Result(column = "id",property = "id"),
            @Result(column = "id",property = "moments",many=@Many(select="com.woniu.woniu_bx.mapper.MomentMapper.findByUserId"))
    })
    List<User> findByMyLikeId(int id);

    //查看详情(动态加评论)
    @Select("select * from bx_moment where id = #{id}")
    @Results({
            @Result(column = "id", property = "id"),
            @Result(column = "user_id", property = "user", one = @One(select = "com.woniu.woniu_bx.mapper.UserMapper.selectById", fetchType = FetchType.LAZY)),
            @Result(column = "id", property = "discuss", one = @One(select = "com.woniu.woniu_bx.mapper.DiscussMapper.findByMomentId"))
    })
    Moment details(int id);

    // 判断动态是否已点赞
    @Select("select count(*) " +
            "from bx_moment_likes " +
            "where user_id = #{userId} " +
            "and moment_id = #{momentId}")
    Integer likes(@Param("userId") Integer userId, @Param("momentId") Integer momentId);

    // 判断动态作者是否已关注
    @Select("select count(*) " +
            "from bx_like " +
            "where user_id = #{userId} " +
            "and belike_id = #{beLikeId}")
    Integer cares(@Param("userId") Integer userId, @Param("beLikeId") Integer beLikeId);


    // 点赞
    @Insert("insert into bx_moment_likes (user_id,moment_id) values (#{userId}, #{momentId})")
    void giveLike(@Param("userId") Integer userId, @Param("momentId") Integer momentId);

    // 消赞
    @Delete("delete from bx_moment_likes where user_id = #{userId} and moment_id = #{momentId}")
    void cancelLike(@Param("userId") Integer userId, @Param("momentId") Integer momentId);

    // 修改点赞数量
    @Update("update bx_moment set like_num = #{likeNum} where id = #{id}")
    void updateLikeNum(@Param("likeNum") Integer likeNum, @Param("id") Integer momentId);

    // 删除动态点赞
    @Delete("delete from bx_moment_likes where moment_id = #{momentId}")
    void deleteLikesByMomentId(Integer momentId);

    // 删除动态图片
    @Delete("delete from bx_moment_img where moment_id =#{momentId}")
    void deleteImagesByMomentId(Integer momentId);

    // 删除动态评论
    @Delete("delete from bx_discuss where moment_id =#{momentId}")
    void deleteDiscussByMomentId(Integer momentId);
}
